package com.jxl.common.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContextUtil {

    /**
     * 定义当前线程的数据储存
     */
    private static final InheritableThreadLocal<Map<String,Object>> THREAD_LOCAL =
            new InheritableThreadLocal<>();

    /**
     * 初始化
     * @return
     */
    private static Map<String,Object> init(){
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map==null){
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }


    /**
     * 设置上下文
     * @param key
     * @param val
     */
    public static void setContext(String key,Object val){
        Map<String, Object> init = init();
        init.put(key,val);
    }


    /**
     * 获取上下文
     * @param key
     * @param key
     */
    public static Object getContext(String key){
        Map<String, Object> init = init();
        return init.get(key);
    }

    /**
     * 清空上下文
     */
    public static void removeContext(){
        THREAD_LOCAL.remove();
    }

    /**
     * 获取用户Id
     * @return
     */
    public static String getUserLoginId(){
      return getContext("loginId").toString();
    }
}
